package com.xilixili.miaomi.wechat.ui;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.marshalchen.ultimaterecyclerview.URLogs;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.itemTouchHelper.SimpleItemTouchHelperCallback;
import com.marshalchen.ultimaterecyclerview.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.xilixili.miaomi.wechat.R;
import com.xilixili.miaomi.wechat.entity.TweetInfo;
import com.xilixili.miaomi.wechat.network.NetworkManager;
import com.xilixili.miaomi.wechat.recyclerview.SimpleAdapter;

import java.util.List;

/**
 * Created by Marshal Chen on 3/8/2016.
 */
public class LauncherActivity extends AppCompatActivity implements ActionMode.Callback {
    UltimateRecyclerView ultimateRecyclerView;
    SimpleAdapter simpleRecyclerViewAdapter = null;
    LinearLayoutManager linearLayoutManager;
    //int moreNum = 2;
    private ActionMode actionMode;

    Toolbar toolbar;

    private ItemTouchHelper mItemTouchHelper;
    private NetworkManager networkManager;
    private static final int REFRESH = 3;
    private static final int UPDATE = 4;
    //private static final int REFREASH_UI  = 1;
    //private static final int UPDATE_UI  = 2;
    private int status = 0;
    //private List<TweetInfo> list;
    //private Handler handler;

    private NetworkManager.TweetsLister lister = new NetworkManager.TweetsLister(){

        @Override
        public void getTweetInfos(final List<TweetInfo> list) {
            if(list == null) {
                return;
            }
            //LauncherActivity.this.list = list;
            if(simpleRecyclerViewAdapter == null) {
                simpleRecyclerViewAdapter = new SimpleAdapter(list, LauncherActivity.this);

                linearLayoutManager = new LinearLayoutManager(LauncherActivity.this);
                ultimateRecyclerView.setLayoutManager(linearLayoutManager);

                StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(simpleRecyclerViewAdapter);
                ultimateRecyclerView.addItemDecoration(headersDecor);

                ultimateRecyclerView.setLoadMoreView(LayoutInflater.from(LauncherActivity.this)
                        .inflate(R.layout.custom_bottom_progressbar, null));
                ultimateRecyclerView.setParallaxHeader(getLayoutInflater().inflate(R.layout.parallax_recyclerview_header, ultimateRecyclerView.mRecyclerView, false));
                ultimateRecyclerView.setOnParallaxScroll(new UltimateRecyclerView.OnParallaxScroll() {
                    @Override
                    public void onParallaxScroll(float percentage, float offset, View parallax) {
                        Drawable c = toolbar.getBackground();
                        c.setAlpha(Math.round(127 + percentage * 128));
                        toolbar.setBackgroundDrawable(c);
                    }
                });
                ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffffff"));
                ultimateRecyclerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                status = REFRESH;
                                networkManager.getTweetInfos(lister);
                                //handler.sendEmptyMessage(REFREASH_UI);
                                //simpleRecyclerViewAdapter.insert(moreNum++ + "  Refresh things", 0);
                                //ultimateRecyclerView.setRefreshing(false);
                                //linearLayoutManager.scrollToPosition(0);
                                //for(int i = 0; i < list.size(); i ++) {
                                //    simpleRecyclerViewAdapter.insert(list.get(i), i);
                                //}
                                //linearLayoutManager.scrollToPosition(0);
                            }
                        }, 1000);
                    }
                });

                ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(simpleRecyclerViewAdapter);
                mItemTouchHelper = new ItemTouchHelper(callback);
                mItemTouchHelper.attachToRecyclerView(ultimateRecyclerView.mRecyclerView);
                simpleRecyclerViewAdapter.setOnDragStartListener(new SimpleAdapter.OnStartDragListener() {
                    @Override
                    public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
                        mItemTouchHelper.startDrag(viewHolder);
                    }
                });
                ultimateRecyclerView.reenableLoadmore();
                ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);

                ultimateRecyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
                    @Override
                    public void loadMore(int itemsCount, final int maxLastVisiblePosition) {
                        final Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            public void run() {
                                //simpleRecyclerViewAdapter.insert("More " + moreNum++, simpleRecyclerViewAdapter.getAdapterItemCount());
                                //simpleRecyclerViewAdapter.insert("More " + moreNum++, simpleRecyclerViewAdapter.getAdapterItemCount());
                                //simpleRecyclerViewAdapter.insert("More " + moreNum++, simpleRecyclerViewAdapter.getAdapterItemCount());
                                status = UPDATE;
                                networkManager.getTweetInfos(lister);
                                //handler.sendEmptyMessage(UPDATE_UI);

                            }
                        }, 1000);
                    }
                });


                ultimateRecyclerView.showFloatingButtonView();
                findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //simpleRecyclerViewAdapter.insert("newly added item", 1);
                    }
                });
            } else {
                //simpleRecyclerViewAdapter.insert(list,);
                try {
                    for(int i = 0; i < list.size(); i ++) {
                        if(status == REFRESH) {
                            simpleRecyclerViewAdapter.insert(list.get(i), 0);
                        } else {
                            simpleRecyclerViewAdapter.insert(list.get(i), simpleRecyclerViewAdapter.getAdapterItemCount());
                        }
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }

        @Override
        public void getBitMap(Bitmap bitmap, int position) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);
        networkManager = new NetworkManager();
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);


        ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
        ultimateRecyclerView.setHasFixedSize(false);

       /* handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what){
                    case REFREASH_UI:
                    case UPDATE_UI:
                        networkManager.getTweetInfos(lister);
                        break;
                    case REFRESH:
                        simpleRecyclerViewAdapter.insert(list.get(0), 0);


                        break;

                }

            /*if(status == UPDATE) {
                //int count = simpleRecyclerViewAdapter.getAdapterItemCount();
                for(int i = 0; i <list.size(); i ++){
                simpleRecyclerViewAdapter.insert(list.get(i), 0);
                }
            } else if(status == REFRESH) {
                //simpleRecyclerViewAdapter.insert(moreNum++ + "  Refresh things", 0);
                ultimateRecyclerView.setRefreshing(false);
                //linearLayoutManager.scrollToPosition(0);


                    simpleRecyclerViewAdapter.insert(list.get(0), 0);
                simpleRecyclerViewAdapter.insert(list.get(0), 0);
                simpleRecyclerViewAdapter.insert(list.get(0), 0);
                simpleRecyclerViewAdapter.insert(list.get(0), 0);
                simpleRecyclerViewAdapter.insert(list.get(0), 0);

                linearLayoutManager.scrollToPosition(0);
            }*/

        //    }
        //};


        networkManager.getTweetInfos(lister);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        URLogs.d("actionmode---" + (mode == null));
        //mode.getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
        //  return false;
    }

    /**
     * Called to refresh an action mode's action menu whenever it is invalidated.
     *
     * @param mode ActionMode being prepared
     * @param menu Menu used to populate action buttons
     * @return true if the menu or action mode was updated, false otherwise.
     */
    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        // swipeToDismissTouchListener.setEnabled(false);
        this.actionMode = mode;
        return false;
    }


    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return false;
    }


    @Override
    public void onDestroyActionMode(ActionMode mode) {
        this.actionMode = null;
    }


    //
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //FastBinding.startactivity(this, item.getItemId());
        return super.onOptionsItemSelected(item);
    }
}
